<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>碰撞检测</title>
		<style>
			* {
				padding: 0;
				margin: 0;
			}

			div {
				width: 200px;
				height: 200px;
				position: fixed;
			}

			#red {
				left: 200px;
				top: 200px;
				background-color: red;
			}

			#blue {
				background-color: blue;
			}

			#red.black, #blue.black {
				background-color: black;
			}

		</style>
	</head>
	<body>

		<div id="red"></div>
		<div id="blue"></div>
		
	</body>
</html>
<script>
	
	// 获取元素
	var redDiv = document.getElementById('red');
	var blueDiv = document.getElementById('blue');

	// 添加点击事件
	redDiv.onmousedown = clickAction;
	blueDiv.onmousedown = clickAction;

	
	// 拖动
	function clickAction(e) {

		var x = e.clientX - this.offsetLeft;
		var y = e.clientY - this.offsetTop;
		var _this = this;

		document.onmousemove = function(e) {
			// console.log(111);
			_this.style.left = e.clientX - x + "px";
			_this.style.top = e.clientY - y + "px";

			// 第一个元素的位置
			var p1 = {
				left: redDiv.offsetLeft,
				right: redDiv.offsetLeft + redDiv.offsetWidth,
				top: redDiv.offsetTop,
				bottom: redDiv.offsetTop + redDiv.offsetHeight
			};

			// 第二个元素的位置
			var p2 = {
				left: blueDiv.offsetLeft,
				right: blueDiv.offsetLeft + blueDiv.offsetWidth,
				top: blueDiv.offsetTop,
				bottom: blueDiv.offsetTop + blueDiv.offsetHeight
			};

			_this.className = isCrash(p1, p2) ? "black" : "";
			_this.style.zIndex = isCrash(p1, p2) ? 1 : 0;

		};

		document.onmouseup = function() {
			this.onmousemove = null;
		};


	}

	// 参数形式 {left: 值, right: 值, top: 值, bottom: 值}
	function isCrash(p1, p2) {

		if (p1.left > p2.right || p1.right < p2.left || p1.top > p2.bottom || p1.bottom < p2.top) return false;

		return true;

	}




</script>




